<?php

class ConfigLoader
{
	private static $paths = array('/lib/config/', '/app/config/');
	private static $suffix = '.config.json';
	
	public static function get_all_values($config_file)
	{
		$found_file = false;
		$found_values = array();
		
		foreach (self::$paths as $key => $path)
		{
			$file = self::get_filename($path, $config_file);
			if (self::file_appears_valid($file))
			{
				$j = json_decode(file_get_contents($file), true);
				if (is_array($j))
				{
					$found_file = true;
					$found_values = array_merge($found_values, $j);
				}
			}
		}
		
		if ($found_file)
			return $found_values;
		else
			return NULL;
	}
	
	public static function get_simple_value($config_file, $key)
	{
		// Look in app/config first, then lib/config
		foreach (self::$paths as $path)
		{
			$file = self::get_filename($path, $config_file);
			if (self::file_appears_valid($file))
			{
				$j = json_decode(file_get_contents($file), true);
				
				if (is_array($j) && array_key_exists($key, $j))
					return $j[$key];
			}
		}
		
		// Hmm, nothing held it.
		return NULL;
	}
	
	private static function get_filename($path, $config_file)
	{
		return SITE_PATH.$path.basename($config_file).self::$suffix;
	}
	
	private static function file_appears_valid($file)
	{
		return file_exists($file)
			&& is_file($file)
			&& is_readable($file);
	}
}

?>